package data.admin;

import dao.SQLiteConnection;
import gui.admin.ReturnWin;
import javax.swing.*;
import java.sql.*;
import static utils.Time.days;
import static utils.Time.getNowTime;

public class Return extends ReturnWin{

    Return(){
        //查询按钮
        getSelect().addActionListener(e->{
            String rid=getT1().getText();
            String ISBN=getT2().getText();
            String bookname=getT3().getText();
            //生成sql语句
            if(!(rid.isEmpty()&&ISBN.isEmpty()&&bookname.isEmpty())){
                String sql1="SELECT Borrow.bid, Reader.rid, Record.ISBN, Book.bookname, Borrow.btime, Reader.rname " +
                        "from Borrow " +
                        "inner join Record on Record.bid=Borrow.bid " +
                        "inner join Reader on Reader.rid=Record.rid " +
                        "inner join Book on Book.ISBN=Record.ISBN " +
                        "where rtime is null";
                if(!rid.isEmpty()){
                    sql1=sql1+" AND rid="+rid;
                }
                if(!ISBN.isEmpty()){
                    sql1=sql1+" AND Borrow.ISBN='"+ISBN+"'";
                }
                if(!bookname.isEmpty()){
                    sql1=sql1+" AND bookname='"+bookname+"'";
                }
                //连接数据库
                SQLiteConnection connection=new SQLiteConnection();
                connection.Connect_SQLite();
                // 读取数据库中的数据
                try {
                    Connection conn = connection.getConnection();
                    Statement stmt = conn.createStatement();
                    ResultSet rs = stmt.executeQuery(sql1);
                    //清除原表格中的内容
                    getModel().setRowCount(0);
                    //添加新数据
                    ResultSetMetaData meta = rs.getMetaData();
                    int columnCount = meta.getColumnCount();
                    // 添加数据
                    while (rs.next()) {
                        Object[] rowData = new Object[columnCount];
                        for (int i = 1; i <= columnCount; i++) {
                            rowData[i - 1] = rs.getObject(i);
                        }
                        getModel().addRow(rowData);
                    }
                    getTable().setModel(getModel());    // 设置表格的数据和显示
                } catch (SQLException ex) {
                    throw new RuntimeException(ex);
                }
                connection.closeConnection();
            }
        });
        //刷新按钮
        getEmpty().addActionListener(e->{
            getT1().setText("");
            getT2().setText("");
            getT3().setText("");
            //清除表格内容
            getModel().setRowCount(0);
            //连接数据库
            SQLiteConnection connection = new SQLiteConnection();
            connection.Connect_SQLite();
            // 读取数据库中的数据
            try {
                Connection conn = connection.getConnection();
                Statement stmt = conn.createStatement();
                ResultSet rs = stmt.executeQuery(
                        "SELECT Borrow.bid, Reader.rid, Record.ISBN, Book.bookname, Borrow.btime, Reader.rname " +
                        "from Borrow " +
                        "inner join Record on Record.bid=Borrow.bid " +
                        "inner join Reader on Reader.rid=Record.rid " +
                        "inner join Book on Book.ISBN=Record.ISBN " +
                        "where rtime is null");
                ResultSetMetaData meta = rs.getMetaData();
                int columnCount = meta.getColumnCount();
                // 添加数据
                while (rs.next()) {
                    Object[] rowData = new Object[columnCount];
                    for (int i = 1; i <= columnCount; i++) {
                        rowData[i - 1] = rs.getObject(i);
                    }
                    getModel().addRow(rowData);
                }
            } catch (SQLException ex) {
                throw new RuntimeException(ex);
            }
            connection.closeConnection();
        });
        //归还按钮
        getReturnbook().addActionListener(e->{
            int row =getTable().getSelectedRow();
            if(row < 0) {
                JOptionPane.showMessageDialog(this, "请选择要还的书");
            }
            else {
                String bid = getTable().getValueAt(row, 0).toString();
                String rid = getTable().getValueAt(row, 1).toString();
                returnBook(bid);
                // 超时检查
                outTime(bid,rid);
            }
        });
    }

    private void returnBook(String bid){
        String rtime=getNowTime();
        SQLiteConnection connection=new SQLiteConnection();
        connection.Connect_SQLite();
        Connection conn=connection.getConnection();
        try {
            String sql="UPDATE Book SET number =number+1 WHERE Book.ISBN=" +
                    "(SELECT ISBN FROM Record WHERE bid="+bid+")";
            PreparedStatement stmt = conn.prepareStatement(sql);
            int rowsUpdated = stmt.executeUpdate();
            if(rowsUpdated>0){
                getEmpty().doClick();
            }
        } catch (SQLException ex) {
            throw new RuntimeException(ex);
        }
        try {
            String sql= "UPDATE Borrow SET rtime ='"+rtime
                    + "' WHERE bid="+bid+" AND rtime IS NULL;";
            PreparedStatement stmt = conn.prepareStatement(sql);
            int rowsUpdated = stmt.executeUpdate();
            if(rowsUpdated>0){
                JOptionPane.showMessageDialog(this,"还书成功");
                getEmpty().doClick();
            }
        } catch (SQLException ex) {
            throw new RuntimeException(ex);
        }
    }
    private void outTime(String bid,String rid){
        SQLiteConnection connection = new SQLiteConnection();
        connection.Connect_SQLite();
        Connection conn = connection.getConnection();
        String rtime;
        String ltime;
        int day;
        try {
            String sql = "SELECT rtime, ltime FROM Borrow WHERE bid ="+bid;
            PreparedStatement stmt = conn.prepareStatement(sql);
            ResultSet rs = stmt.executeQuery();
            if (rs.next()) {
                rtime = rs.getString("rtime");
                ltime = rs.getString("ltime");
                day=days(rtime,ltime);
                System.out.println(day);
                if(day<0){
                    double cost=Math.abs(day)*0.1;
                    String f_cost = String.format("%.2f", cost);
                    sql="UPDATE Borrow SET cost = "+f_cost+" WHERE bid ="+bid;
                    stmt = conn.prepareStatement(sql);
                    int rowsUpdated = stmt.executeUpdate();
                    if(rowsUpdated>0){
                        System.out.println(cost);
                        JOptionPane.showMessageDialog(this,"需缴纳"+f_cost+"元");
                        sql="UPDATE Reader SET state = 1 WHERE rid ='"+rid+"'";
                        stmt = conn.prepareStatement(sql);
                        stmt.executeUpdate();
                    }
                }

            }
            rs.close();
            stmt.close();
            conn.close();

        } catch (SQLException ex) {
            throw new RuntimeException(ex);
        }


    }

    public static void main(String[] args) {
        new Return();
    }
}
